package com.example.zhihu.controller;

import com.example.zhihu.pojo.vo.SocketMsgVO;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class MyWebSocket {


    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
    private Session session;
    private String userId;

    private static Map<String,Session> map = new HashMap<String, Session>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        map.put(userId, session);
        webSocketSet.add(this);

        System.out.println("有人加入:"+userId+"，现在人数为：" + webSocketSet.size());


    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        System.out.println("有链接关闭，当前人数为："+webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") String userId) {
        System.out.println("信息：-->"+userId+":" + message);
        ObjectMapper objectMapper = new ObjectMapper();
        SocketMsgVO socketMsgVO;
        try{
            socketMsgVO = objectMapper.readValue(message, SocketMsgVO.class);
            if(socketMsgVO.getType() == 1) {
                socketMsgVO.setFromUser(userId);
                Session fromSession = map.get(socketMsgVO.getFromUser());
                Session toSession = map.get(socketMsgVO.getToUser());
                if(toSession != null) {
                    fromSession.getAsyncRemote().sendText(message);
                    toSession.getAsyncRemote().sendText(message);
                } else {
                    fromSession.getAsyncRemote().sendText("{\"code\":\"1\",\"msg\":\"本人不在线\"}");
                }
            } else {
                // 群发信息
                 broadCast(message);
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void broadCast(String message) {
        for(MyWebSocket item : webSocketSet) {
            item.session.getAsyncRemote().sendText(message);
        }
    }
}


